package net.plankton.agents.main;

import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import net.plankton.agents.Agent;

public class ThreadedNetOutput implements SurveillanceOutput {

	SurveillanceOutput out;
	
	private OutputStream stream;
	Socket s;
	private Queue<Message> queue = new ConcurrentLinkedQueue<Message>();
	
	public ThreadedNetOutput() {
		
		connect();
		new OutputThread().start();
	}
	
	private void connect() {
		try {
			s = new Socket("127.0.0.1",6668);
			stream = s.getOutputStream();
		}
		catch (Exception e) {
			
		}
	}
	public void output(Agent a,String output) {
		queue.offer(new Message(a,output));

	}

	
	class OutputThread extends Thread {
		@Override
		public void run() {
			while (true) {
				try {
					Message val = queue.poll();
					if (val!=null) {
						if (stream==null || !s.isConnected()) {
							connect();
						}
						else {
							String message;
							if (val.getAgent()!=null) {
								message = val.getAgent().describe()+">  "+val.getMessage()+"\n";
							}
							else {
								message = val.getMessage()+"\n";
							}
							stream.write(message.getBytes("UTF-8"));
						}
					}
					Thread.sleep(1500);
				}
				catch (SocketException e) {
					connect();
				}
				catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	class Message {
		private Agent a;
		private String mess;

		public Message(Agent a,String mess) {
			this.a=a;
			this.mess=mess;
		}
		
		public Agent getAgent() {
			return a;
		}
		public String getMessage() {
			return mess;
		}
	}
	
}
